package user

import (
	"errors"
	"github.com/gin-gonic/gin"
	"net/http"
)

import (
	"bainiao/internal/db"
	"bainiao/internal/model"
	"errors"
	"github.com/gin-gonic/gin"
	"net/http"
)

// Register 用户注册
func Register(c *gin.Context) {
	var req struct {
		Username string `json:"username"`
		Password string `json:"password"`
		Email    string `json:"email"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 检查用户名是否已存在
	var existingUser model.User
	if err := db.DB.Where("username = ?", req.Username).First(&existingUser).Error; err == nil {
		c.JSON(http.StatusConflict, gin.H{"error": "用户名已存在"})
		return
	}

	// 创建新用户
	user := model.User{
		Username: req.Username,
		Password: req.Password,
		Email:    req.Email,
	}
	if err := db.DB.Create(&user).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "注册失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "注册成功", "userID": user.ID})
}

// AddFriend 添加好友请求
func AddFriend(c *gin.Context) {
	var req struct {
		UserID   uint   `json:"user_id"`
		FriendID uint   `json:"friend_id"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 检查是否已存在关系
	var existingRelation model.FriendRelation
	if err := db.DB.Where("(user_id = ? AND friend_id = ?) OR (user_id = ? AND friend_id = ?)", req.UserID, req.FriendID, req.FriendID, req.UserID).First(&existingRelation).Error; err == nil {
		c.JSON(http.StatusConflict, gin.H{"error": "关系已存在"})
		return
	}

	// 创建好友请求
	relation := model.FriendRelation{
		UserID:   req.UserID,
		FriendID: req.FriendID,
		Status:   "pending",
	}
	if err := db.DB.Create(&relation).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "请求发送失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{"message": "好友请求已发送"})
}

// WechatLogin 微信登录接口
func WechatLogin(c *gin.Context) {
	var req struct {
		Code string `json:"code"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error":"参数错误"})
		return
	}

	// 调用微信接口获取OpenID（示例使用固定参数，实际应从环境变量获取）
	appID := "wx1234567890abcdef" // 替换为实际appID
	secret := "1234567890abcdef1234567890abcdef" // 替换为实际secret
	url := fmt.Sprintf("https://api.weixin.qq.com/sns/jscode2session?appid=%s&secret=%s&js_code=%s&grant_type=authorization_code", appID, secret, req.Code)

	resp, err := http.Get(url)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error":"微信接口调用失败"})
		return
	}
	defer resp.Body.Close()

	var wxResp struct {
		OpenID string `json:"openid"`
		ErrCode int `json:"errcode"`
		ErrMsg string `json:"errmsg"`
	}
	if err := json.NewDecoder(resp.Body).Decode(&wxResp); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error":"微信响应解析失败"})
		return
	}

	if wxResp.ErrCode != 0 {
		c.JSON(http.StatusBadRequest, gin.H{"error":fmt.Sprintf("微信错误: %d %s", wxResp.ErrCode, wxResp.ErrMsg)})
		return
	}

	// 查询是否已关联微信用户
	var user model.User
	if err := db.DB.Where("wechat_open_id = ?", wxResp.OpenID).First(&user).Error; err == nil {
		// 已存在用户，返回登录信息
		c.JSON(http.StatusOK, gin.H{
			"message":"微信登录成功",
			"userID": user.ID,
			"username": user.Username,
			"avatar": user.Avatar,
		})
		return
	}

	// 新用户自动注册（可根据需求补充其他用户信息）
	newUser := model.User{
		Username:  fmt.Sprintf("wx_user_%s", wxResp.OpenID[:8]),
		Password:  "", // 微信登录无密码
		Avatar:    "", // 可通过微信接口获取头像
		WechatOpenID: wxResp.OpenID,
	}
	if err := db.DB.Create(&newUser).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error":"自动注册失败"})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"message":"微信登录成功（新用户自动注册）",
		"userID": newUser.ID,
		"username": newUser.Username,
		"avatar": newUser.Avatar,
	})
}

// Login 用户登录
func Login(c *gin.Context) {
	var req struct {
		Username string `json:"username"`
		Password string `json:"password"`
	}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	// 查询数据库用户
	var user model.User
	if err := db.DB.Where("username = ?", req.Username).First(&user).Error; err != nil {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "用户名或密码错误"})
		return
	}

	// 验证密码（示例明文验证，实际应使用哈希）
	if user.Password != req.Password {
		c.JSON(http.StatusUnauthorized, gin.H{"error": "用户名或密码错误"})
		return
	}

	// 登录成功返回用户ID和基础信息
	c.JSON(http.StatusOK, gin.H{
		"message": "登录成功",
		"userID": user.ID,
		"username": user.Username,
		"avatar": user.Avatar,
	})
}

// GetUserInfo 获取用户信息
func GetUserInfo(c *gin.Context) {
	username := c.Query("username")
	user, exists := users[username]
	if !exists {
		c.JSON(http.StatusNotFound, gin.H{"error": "用户不存在"})
		return
	}
	c.JSON(http.StatusOK, user)
}